using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public enum GuideType
{
    Rect,
    Circle
}

[RequireComponent(typeof(Image))]
public abstract class GuideBase : MonoBehaviour
{
    public abstract GuideType guideType { get; }
    /// <summary> 画布 </summary>
    public Canvas canvas;
    /// <summary> 蒙板材质 </summary>
    protected Material material;
    /// <summary> 镂空区域 </summary>
    protected RectTransform target;
    /// <summary> 存储要镂空组件的四个角的数组 </summary>
    protected Vector3[] targetCorners;
    /// <summary> 镂空区域中心 </summary>
    protected Vector3 center;

    private void Awake()
    {
        targetCorners = new Vector3[4];
        target ??= transform.GetComponent<RectTransform>();
        material ??= transform.GetComponent<Image>().material;
    }

    //private void Update()
    //{
    //    if (Input.GetKeyDown(KeyCode.Y))
    //    {
    //        Guide(canvas, target);
    //    }
    //}

    // 引导
    public virtual void Guide(RectTransform target)
    {
        this.target = target;  // 将传进来的目标组件赋值给target

        // 获取中心点
        // GetWorldCorners:在世界空间中得到计算的矩形的角。参数角的数组
        target.GetWorldCorners(targetCorners);

        // 讲四个角的世界坐标转为局部坐标坐标
        for (int i = 0; i < targetCorners.Length; i++)
            targetCorners[i] = WorldToScreenPoint(canvas, targetCorners[i]);

        //计算中心点
        center.x = targetCorners[0].x + (targetCorners[3].x - targetCorners[0].x) / 2;
        center.y = targetCorners[0].y + (targetCorners[1].y - targetCorners[0].y) / 2;
        //设置材质的中心点
        material.SetVector("_Center", center);
    }

    public Vector2 WorldToScreenPoint(Canvas canvas, Vector3 world)
    {
        //把世界坐标转化为屏幕坐标
        Vector2 screenPoint = RectTransformUtility.WorldToScreenPoint(canvas.worldCamera, world);

        // 屏幕坐标转换为局部坐标
        //out的是vector2类型，事先声明
        RectTransformUtility.ScreenPointToLocalPointInRectangle
            (canvas.GetComponent<RectTransform>(), screenPoint, canvas.worldCamera, out Vector2 localPoint);
        return localPoint;
    }
}